﻿Imports OMANE.moteurTauxGaranti2
Imports PTIC_Util

Public Class frmResultatsModele2simul
    Implements IObserver

    Protected _moteur2 As Moteur_Methode2
    Protected _Simulations As simulationsMoteur2

    Public Sub New(ByVal moteur2 As Moteur_Methode2)

        InitializeComponent()
        _Simulations = moteur2.Simulations
        _moteur2 = moteur2

        BindingSourceSimul.DataSource = _Simulations.ListeFonctionsCalculIntermediaires
        dgvSimul.AutoGenerateColumns = False
        dgvSimul.DataSource = BindingSourceSimul
        dgvSimul.Columns("ColId").DataPropertyName = "Description"
        dgvSimul.Columns("ColEtatSimul").DataPropertyName = "etatCalcul"
        dgvSimul.Columns("ColTemps").DataPropertyName = "TempsCalcul"
        txtIdSimul.DataBindings.Add("Text", BindingSourceSimul, "Description")
        BindingSourceSimul.AllowNew = True

        dgvParam.AutoGenerateColumns = False
        dgvParam.DataSource = BindingSourceParam

        'Aliementation de la liste de choix des paramètres
        Dim colDecrParametre As DataGridViewComboBoxColumn = dgvParam.Columns("ColNomParametre")
        Dim query = From param In _moteur2.listeParametres _
                    Where param.Value.methode_Cal(1) = True _
                        And param.Value.nom <> "Table_Mortalite_F" _
                        And param.Value.nom <> "Table_Mortalite_H" _
                        And param.Value.nom <> "franchise_INCAP" _
                        And param.Value.nom <> "TxMort_Actu" _
                        And param.Value.nom <> "tble_maintien_incinvFRA" _
                        And param.Value.nom <> "Grille_Tarif" _
                        And param.Value.nom <> "tble_maintien_incinvM2" _
                        And param.Value.nom <> "Pres_GarantiePTIA" _
                    Select param.Value.nom
        colDecrParametre.DataSource = query.ToList
        AddHandler _Simulations.listeSimulations_HasChanged, AddressOf onListeSimulationsHasChanged
    End Sub

    Private Sub BindingSourceSimul_AddingNew(ByVal sender As Object, _
                                                   ByVal e As System.ComponentModel.AddingNewEventArgs) _
                                                   Handles BindingSourceSimul.AddingNew
        Dim newSimulation As simulationIndivMoteur2 = _
            New simulationIndivMoteur2(_moteur2, True)
        newSimulation.Description = "Perso"
        e.NewObject = newSimulation
    End Sub
    Private Sub BindingSourceSimul_CurrentItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BindingSourceSimul.CurrentItemChanged
        BindingSourceParam.DataSource = CType(BindingSourceSimul.Current, simulationIndivMoteur2).listeParametres
        dgvParam.Columns("ColNomParametre").DataPropertyName = "Nom"
        dgvParam.Columns("colValMin").DataPropertyName = "chocMin"
        dgvParam.Columns("colValMax").DataPropertyName = "chocMax"
        dgvParam.Columns("ColPas").DataPropertyName = "Pas"
    End Sub
    Private Sub BindingSourceParam_AddingNew(ByVal sender As Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles BindingSourceParam.AddingNew
        Dim newParam As ParametreSimulationIndiv = New ParametreSimulationIndiv("")
        newParam.chocMax = 0
        newParam.chocMin = 0
        newParam.Pas = 0
        e.NewObject = newParam
    End Sub

    Private Sub dgvSimul_CellContentClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvSimul.CellContentClick
        If IsANonHeaderButtonCell(e) Then
            Dim numSimul As Integer = e.RowIndex
            Dim simul As simulationIndivMoteur2 = _Simulations.ListeFonctionsCalculIntermediaires(numSimul)
            Dim descrSimul As String = simul.Description
            simul.Calculer()
            simul.AjouteFonctionCalculIntermediaire(_moteur2.scenarioCentral)
        End If
    End Sub
    Private Sub ajouteOngletSimul(ByVal simul As simulationIndivMoteur2)

        Dim descrSimul As String = simul.Description
        Dim zedGraphSimul As New ZedGraph.ZedGraphControl
        Dim tabPageSimul As tabPageSimul = New tabPageSimul(simul)
        tabPageSimul.Name = "tabSimul" & descrSimul
        tabPageSimul.Text = "SIMULATION " & descrSimul
        tbc_ImportEncours.TabPages.Add(tabPageSimul)
        Dim dgvChoixParam As New DataGridView
        Dim dgvSimulation As New DataGridView
        Dim ComboBoxParamSimul As New System.Windows.Forms.ComboBox
        Dim aPlusieursParam As Boolean = (simul.listeParametres.Count >= 2)
        Dim hauteurReservee As Integer = 100
        ''aPlusieursParam = True 'Test
        '
        'ComboBoxParam
        '
        ComboBoxParamSimul.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
        ComboBoxParamSimul.FormattingEnabled = True
        ComboBoxParamSimul.Location = New System.Drawing.Point(22, 22)
        ComboBoxParamSimul.Name = "ComboBoxParamSimul"
        ComboBoxParamSimul.Size = New System.Drawing.Size(191, 22)
        ComboBoxParamSimul.TabIndex = 2
        ComboBoxParamSimul.BeginUpdate()
        For Each param As ParametreSimulationIndiv In simul.listeParametres
            ComboBoxParamSimul.Items.Add(param.Nom)
        Next
        ComboBoxParamSimul.EndUpdate()
        AddHandler ComboBoxParamSimul.SelectedValueChanged, AddressOf Me.onComboBoxChoixParamChanged
        '
        'PanelBordsSimul
        '
        Dim PanelBordsSimul As New PTIC_Composants_WF.PTIC_Panel
        PanelBordsSimul.BackColorAxeDegrade = 0
        PanelBordsSimul.BackColorDegrade11 = System.Drawing.Color.Empty
        PanelBordsSimul.BackColorDegrade12 = System.Drawing.Color.Empty
        PanelBordsSimul.BackColorDegrade21 = System.Drawing.Color.Empty
        PanelBordsSimul.BackColorDegrade22 = System.Drawing.Color.Empty
        PanelBordsSimul.BackColorPerso = False
        PanelBordsSimul.BorderBottom = True
        PanelBordsSimul.BorderColor_bottom = System.Drawing.Color.Empty
        PanelBordsSimul.BorderColor_Left = System.Drawing.Color.Empty
        PanelBordsSimul.BorderColor_right = System.Drawing.Color.Empty
        PanelBordsSimul.BorderColor_top = System.Drawing.Color.Empty
        PanelBordsSimul.BorderLeft = True
        PanelBordsSimul.BorderPerso = False
        PanelBordsSimul.BorderRight = True
        PanelBordsSimul.BorderTop = True
        PanelBordsSimul.Controls.Add(dgvSimulation)
        PanelBordsSimul.Controls.Add(zedGraphSimul)
        '
        If aPlusieursParam Then PanelBordsSimul.Controls.Add(ComboBoxParamSimul)
        If aPlusieursParam Then PanelBordsSimul.Controls.Add(dgvChoixParam)
        PanelBordsSimul.degrade = PTIC_Composants_WF.PTIC_Panel.typeDegrade.AERO
        PanelBordsSimul.Dock = System.Windows.Forms.DockStyle.Fill
        PanelBordsSimul.Location = New System.Drawing.Point(0, 0)
        PanelBordsSimul.Margin = New System.Windows.Forms.Padding(0)
        PanelBordsSimul.Name = "PtiC_PanelBordsSimul" & descrSimul
        PanelBordsSimul.TabIndex = 2
        PanelBordsSimul.theme = PTIC_Composants_WF.PTIC_Panel.nomThemePanel.OMANEtabControl
        '
        'tabPageSimul
        '
        tabPageSimul.Controls.Add(PanelBordsSimul)
        '
        'dgvSimul
        '
        dgvSimulation.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or _
                                   System.Windows.Forms.AnchorStyles.Bottom) _
                                   Or System.Windows.Forms.AnchorStyles.Left) _
                                   Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        dgvSimulation.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
        dgvSimulation.Location = New System.Drawing.Point(22, 22 + IIf(aPlusieursParam, hauteurReservee, 0))
        dgvSimulation.Name = "dgvSimul" & descrSimul
        dgvSimulation.Size = New System.Drawing.Size((tabPageSimul.Width - 66) / 2, tabPageSimul.Height - 44 - IIf(aPlusieursParam, hauteurReservee, 0))
        dgvSimulation.TabIndex = 0
        dgvSimulation.DataSource = simul.Resultats
        dgvSimulation.Columns("VAN").DefaultCellStyle.Format = "#,### €"
        dgvSimulation.Columns("TRI").DefaultCellStyle.Format = "#,##0.# %"
        dgvSimulation.AllowUserToAddRows = False
        dgvSimulation.AllowUserToDeleteRows = False
        dgvSimulation.ReadOnly = True
        dgvSimulation.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
        '
        'DgvChoixParam
        '
        dgvChoixParam.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top) _
                                   Or System.Windows.Forms.AnchorStyles.Left) _
                                   Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        dgvChoixParam.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
        dgvChoixParam.Location = New System.Drawing.Point(22, 22 + 31)
        dgvChoixParam.Name = "dgvChoixParam" & descrSimul
        dgvChoixParam.Size = New System.Drawing.Size((tabPageSimul.Width - 66) / 2, hauteurReservee - 40)
        dgvChoixParam.AllowUserToAddRows = False
        dgvChoixParam.AllowUserToDeleteRows = False
        dgvChoixParam.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
        AddHandler dgvChoixParam.CellValueChanged, AddressOf Me.onChoixParamChanged
        '
        'zedGraphSimul
        '
        zedGraphSimul.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top _
                                        Or System.Windows.Forms.AnchorStyles.Bottom)) _
                                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        zedGraphSimul.Location = New System.Drawing.Point(((tabPageSimul.Width - 66) / 2) + 44, _
                                                          22)
        zedGraphSimul.Name = "ZedGraphSimul" & descrSimul
        zedGraphSimul.ScrollGrace = 0
        zedGraphSimul.ScrollMaxX = 0
        zedGraphSimul.ScrollMaxY = 0
        zedGraphSimul.ScrollMaxY2 = 0
        zedGraphSimul.ScrollMinX = 0
        zedGraphSimul.ScrollMinY = 0
        zedGraphSimul.ScrollMinY2 = 0
        zedGraphSimul.Size = New System.Drawing.Size((tabPageSimul.Width - 66) / 2, tabPageSimul.Height - 44)
        zedGraphSimul.TabIndex = 1

        If Not aPlusieursParam Then MAJ_graphiques(zedGraphSimul, simul)
    End Sub

    Private Sub onComboBoxChoixParamChanged(ByVal sender As Object, ByVal e As EventArgs)

        Dim tabPageSimulEnCours As tabPageSimul = Me.tbc_ImportEncours.TabPages(CType(sender, ComboBox).Parent.Parent.Name)
        Dim simul As simulationIndivMoteur2 = tabPageSimulEnCours.simulation
        Dim panelBordsSimul As Panel = CType(tabPageSimulEnCours.Controls("PtiC_PanelBordsSimul" & simul.Description), Panel)
        Dim zedGraphSimul As ZedGraph.ZedGraphControl = panelBordsSimul.Controls("ZedGraphSimul" & simul.Description)

        Dim tableValFixeParam As New DataTable
        For Each param As ParametreSimulationIndiv In simul.listeParametres
            If param.Nom <> CType(panelBordsSimul.Controls("ComboBoxParamSimul"), ComboBox).SelectedItem Then
                tableValFixeParam.Columns.Add(param.Nom, GetType(Double))
            End If
        Next
        Dim newRow As DataRow = tableValFixeParam.NewRow
        For Each param As ParametreSimulationIndiv In simul.listeParametres
            If param.Nom <> CType(panelBordsSimul.Controls("ComboBoxParamSimul"), ComboBox).SelectedItem Then
                newRow(param.Nom) = 0
            End If
        Next
        tableValFixeParam.Rows.Add(newRow)

        CType(panelBordsSimul.Controls("dgvChoixParam" & simul.Description), DataGridView).DataSource = tableValFixeParam
        MAJ_graphiques(zedGraphSimul, simul)
    End Sub
    Private Sub onChoixParamChanged(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
        'Comment mettre à jour le tableau des valeurs et les graphiques ?
        ' - A l'initialisation
        ' - Lors de la modification : du paramètre de référence, de point de référence
        'Récupérer les références du ZedGraphSimul et simul en cours
        Dim tabPageSimulEnCours As tabPageSimul = sender.Parent.Parent
        Dim simul As simulationIndivMoteur2 = tabPageSimulEnCours.simulation
        Dim panelBordsSimul As Panel = CType(tabPageSimulEnCours.Controls("PtiC_PanelBordsSimul" & simul.Description), Panel)
        Dim zedGraphSimul As ZedGraph.ZedGraphControl = panelBordsSimul.Controls("ZedGraphSimul" & simul.Description)
        MAJ_graphiques(zedGraphSimul, simul)
    End Sub
    Private Sub onListeSimulationsHasChanged(ByVal sender As Object, _
                                             ByVal notification As simulationsMoteur2.listeSimulationsEventArgs)
        Dim typeModif As simulationsMoteur2.listeSimulationsEventArgs.natureModifications
        typeModif = notification.natureModif
        If typeModif = simulationsMoteur2.listeSimulationsEventArgs.natureModifications.EtatCalcul Or _
           typeModif = simulationsMoteur2.listeSimulationsEventArgs.natureModifications.Ajout Or _
           typeModif = simulationsMoteur2.listeSimulationsEventArgs.natureModifications.Suppression Then
            refreshAffichage()
        End If
    End Sub

    Private Sub MAJ_graphiques(ByVal zedGraphSimul As ZedGraph.ZedGraphControl, ByVal simul As simulationIndivMoteur2)
        'Faire un filtre sur les valeurs indiquées dans le tableau de paramètres
        'A partir de ce filtre, on met à jour les graphiques
        Dim tabPageSimulEnCours As TabPage = Me.tbc_ImportEncours.TabPages(zedGraphSimul.Parent.Parent.Name)
        Dim master As ZedGraph.MasterPane = zedGraphSimul.MasterPane
        master.PaneList.Clear()
        master.Title.IsVisible = False
        master.Margin.All = 10
        Dim GPaneTRI As ZedGraph.GraphPane = getGPaneTRI(simul, tabPageSimulEnCours)
        Dim GPaneVAN As ZedGraph.GraphPane = getGPaneVAN(simul, tabPageSimulEnCours)
        master.Title.Text = "Synthèse des résultats de la simulation"
        master.Add(GPaneTRI)
        master.Add(GPaneVAN)
        zedGraphSimul.AxisChange()
        Dim g As Graphics = Me.CreateGraphics
        master.SetLayout(g, ZedGraph.PaneLayout.SingleColumn)
        zedGraphSimul.Invalidate()
    End Sub
    Private Function getGPaneTRI(ByVal simul As simulationIndivMoteur2, ByVal tabPageSimulEnCours As TabPage) As ZedGraph.GraphPane

        Dim aPlusieursParam As Boolean = (simul.listeParametres.Count >= 2)
        Dim dgvChoixParam As DataGridView = New DataGridView
        Dim nomParamEnCours As String

        If aPlusieursParam Then
            nomParamEnCours = CType(CType(tabPageSimulEnCours.Controls("PtiC_PanelBordsSimul" & simul.Description), Panel).Controls("ComboBoxParamSimul"), ComboBox).SelectedItem
            dgvChoixParam = tabPageSimulEnCours.Controls("PtiC_PanelBordsSimul" & simul.Description).Controls("dgvChoixParam" & simul.Description)
        Else
            nomParamEnCours = CType(simul.listeParametres.Item(0), ParametreSimulationIndiv).Nom
        End If

        Dim GpaneTRI As New ZedGraph.GraphPane()
        Dim listeTRI As New ZedGraph.PointPairList
        For Each rowResultat As DataRow In simul.Resultats.Rows
            'On vérifie que le filtre est vérifié
            Dim aInclure As Boolean = True
            If aPlusieursParam Then
                For Each col As DataGridViewColumn In dgvChoixParam.Columns
                    If CDbl(rowResultat(col.Name)) <> CDbl(dgvChoixParam(col.Index, 0).Value) Then
                        aInclure = False
                    End If
                Next
                If aInclure Then listeTRI.Add(rowResultat(nomParamEnCours), rowResultat("TRI"))
            Else
                listeTRI.Add(rowResultat(nomParamEnCours), rowResultat("TRI"))
            End If
        Next
        Dim ligneTRI As ZedGraph.LineItem
        ligneTRI = GpaneTRI.AddCurve("TRI", listeTRI, Color.Blue, ZedGraph.SymbolType.Diamond)
        miseEnFormeGraph(GpaneTRI, "TRI (taux de rendement interne)", "Choc", "TRI", 20)
        ligneTRI.Line.Width = 1.75F
        Return GpaneTRI
    End Function
    Private Function getGPaneVAN(ByVal simul As simulationIndivMoteur2, ByVal tabPageSimulEnCours As TabPage) As ZedGraph.GraphPane

        Dim aPlusieursParam As Boolean = (simul.listeParametres.Count >= 2)
        Dim dgvChoixParam As DataGridView = New DataGridView
        Dim nomParamEnCours As String

        If aPlusieursParam Then
            nomParamEnCours = CType(CType(tabPageSimulEnCours.Controls("PtiC_PanelBordsSimul" & simul.Description), Panel).Controls("ComboBoxParamSimul"), ComboBox).SelectedItem
            dgvChoixParam = tabPageSimulEnCours.Controls("PtiC_PanelBordsSimul" & simul.Description).Controls("dgvChoixParam" & simul.Description)
        Else
            nomParamEnCours = CType(simul.listeParametres.Item(0), ParametreSimulationIndiv).Nom
        End If

        Dim GpaneVAN As New ZedGraph.GraphPane()
        Dim listeVAN As New ZedGraph.PointPairList

        For Each rowResultat As DataRow In simul.Resultats.Rows
            'On vérifie que le filtre est vérifié
            Dim aInclure As Boolean = True
            If aPlusieursParam Then
                For Each col As DataGridViewColumn In dgvChoixParam.Columns
                    If CDbl(rowResultat(col.Name)) <> CDbl(dgvChoixParam(col.Index, 0).Value) Then
                        aInclure = False
                    End If
                Next
                If aInclure Then listeVAN.Add(rowResultat(nomParamEnCours), rowResultat("VAN"))
            Else
                listeVAN.Add(rowResultat(nomParamEnCours), rowResultat("VAN"))
            End If
        Next

        Dim ligneTRI As ZedGraph.LineItem
        ligneTRI = GpaneVAN.AddCurve("VAN", listeVAN, Color.Red, ZedGraph.SymbolType.Diamond)
        miseEnFormeGraph(GpaneVAN, "VAN (valeur actuelle nette)", "Choc", "VAN", 20, "#,### €")
        ligneTRI.Line.Width = 1.75F
        Return GpaneVAN
    End Function
    Private Function IsANonHeaderButtonCell(ByVal cellEvent As  _
            DataGridViewCellEventArgs) As Boolean

        If TypeOf dgvSimul.Columns(cellEvent.ColumnIndex) _
            Is DataGridViewButtonColumn _
            AndAlso Not cellEvent.RowIndex = -1 Then _
            Return True Else Return (False)

    End Function
    Public Function actualise(ByVal sender As Object, ByVal notification As Object) As PTIC_Util.resultatValidationContraintes Implements PTIC_Util.IObserver.actualise
        Return Nothing
    End Function
    Private Sub refreshAffichage()
        For Each simul As simulationIndivMoteur2 In _Simulations.ListeFonctionsCalculIntermediaires
            If simul.etatCalcul = valueEtatCalcul.A_JOUR Then
                If Not tbc_ImportEncours.TabPages.ContainsKey("tabSimul" & simul.Description) Then
                    ajouteOngletSimul(simul)
                End If
            Else
                If tbc_ImportEncours.TabPages.ContainsKey("tabSimul" & simul.Description) Then
                    tbc_ImportEncours.TabPages.RemoveByKey("tabSimul" & simul.Description)
                End If
            End If
        Next

        Dim queryOnglets = From tbp As TabPage In tbc_ImportEncours.TabPages _
                           Where tbp.Name <> "tbp_Simulations" _
                           Select Microsoft.VisualBasic.Right(tbp.Name, tbp.Name.Length - 8)
        Dim queryDescSim = From simul As simulationIndivMoteur2 In _Simulations.ListeFonctionsCalculIntermediaires _
                           Where simul.etatCalcul = valueEtatCalcul.A_JOUR _
                           Select simul.Description

        Dim listeDesc As String() = queryDescSim.ToArray
        Dim listeOnglets As String() = queryOnglets.ToArray
        For Each onglet As String In listeOnglets
            If Not listeDesc.Contains(onglet) Then tbc_ImportEncours.TabPages.RemoveByKey("tabSimul" & onglet)
        Next

    End Sub
    Private Sub frmResultatsModele2_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        RemoveHandler _Simulations.listeSimulations_HasChanged, AddressOf onListeSimulationsHasChanged
    End Sub

    Private Class tabPageSimul
        Inherits Windows.Forms.TabPage
        Protected _simul As simulationIndivMoteur2
        Public Sub New(ByVal simul As simulationIndivMoteur2)
            MyBase.New()
            _simul = simul
        End Sub
        Public ReadOnly Property simulation() As simulationIndivMoteur2
            Get
                Return _simul
            End Get
        End Property
    End Class

End Class